package cm.example.shoppingplatformspringboot.service;

import cm.example.shoppingplatformspringboot.mapper.OrderMapper;
import cm.example.shoppingplatformspringboot.utils.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private OrderMapper orderMapper;

    public String createAlipayOrder(String orderNo, String subject) {
        try {
            // 创建支付请求
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

            // 设置异步通知地址
            request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
            // 设置同步返回地址
            request.setReturnUrl(AlipayConfig.RETURN_URL);

            String totalAmount = orderMapper.selectOrderNo(orderNo).getTotal_money().toString();

            // 构建请求参数
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");

            request.setBizModel(model);

            // 使用GET方式获取支付表单
            return alipayClient.pageExecute(request, "GET").getBody();//支付宝支付页面的地址
        } catch (AlipayApiException e) {
            throw new RuntimeException("支付宝支付异常", e);
        }
    }
}